const { splitTrainingText } = require('../splite.js');
Page({
  data: {
    HistoryList: [], 
    userInfo:{},
    loading: false ,
    pid:0,
    text_query:'',
    text_answer:'',
    splitResult:''
  },
  onLoad() {
    this.getPid();
  },
  splitText() {
    console.log("回答是：",this.data.text_answer)
    const answer = splitTrainingText(this.data.text_answer)
    const total = answer.items.length
    this.setData({
      splitResult: answer,
      // 初始化状态数组，所有项目默认为"未开始"
      trainingStatus: new Array(answer.items.length).fill(0),
      totalCount: total,
      completedCount: 0,
      progressPercent: 0
    });
    wx.setStorageSync('total', total)
  },
  getPid() {
    const userInfo = wx.getStorageSync('userInfo')
    this.setData({
      userInfo:userInfo
    })
    wx.request({
      url: getApp().globalData.baseUrl + '/api/plan/uid/'+this.data.userInfo.data.id,
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      success: (res) => {
        console.log("历史计划返回值：",res.data)
        // 请求成功处理
        if (res.data.code==200) { 
          this.setData({
            pid: res.data.data.id,
            loading: false
          });
          console.log("pid:",this.data.pid)
          this.getHistoryPlans()
        } else {
          wx.showToast({
            title: res.data.msg || '获取数据失败',
            icon: 'none'
          });
          this.setData({
            loading: false
          });
        }
      },
      fail: (err) => {
        // 请求失败处理
        console.error('获取历史计划失败', err);
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
        this.setData({
          loading: false
        });
      }
    });
  },
  getHistoryPlans(){
    const requestData = {
      prompt:'',
      response:'',
      id: this.data.userInfo.data.id,
      target:'',
      preference:'',
      duration:'',
    };
    wx.request({
      url: getApp().globalData.baseUrl + '/api/History/getHistory',
      method: 'POST',
      data:requestData,
      header: {
        'content-type': 'application/json'
      },
      success: (res) => {
        console.log("聊天返回值：",res.data.data)
        // 请求成功处理
        if (res.data) { 
          this.setData({
            HistoryList: res.data.data,
            text_query:res.data.data.query,
            text_answer:res.data.data.answer,
            loading: false
          });
          this.splitText();
        } else {
          wx.showToast({
            title: res.data.msg || '获取数据失败',
            icon: 'none'
          });
          this.setData({
            loading: false
          });
        }
      },
      fail: (err) => {
        // 请求失败处理
        console.error('获取历史计划失败', err);
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
        this.setData({
          loading: false
        });
      }
    });
  },
});